<template>
  <Spin :spinning="loading1" tip="Loading...">
    <div>
      <!-- 图解系统维护 -->
      <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="4" :collapse="collapse" labelWidth="90" @filterChange="changeHandle"></TopFilter>
      <!-- table -->
      <Spin :spinning="loading" tip="导入中，请稍后...">
        <FilterTable
          ref="table"
          :columns="columns"
          :params="fetchParams"
          :fetchapi="fetchapi"
          :datakey="'records'"
          :onColumnsChange="(columns) => (this.columns = columns)"
          :onRowSelectChange="selectChange"
          :isExportExcel2="true"
          :exportFileName="'图解车型信息.xlsx'"
        >
          <template slot="controls" slot-scope="props">
            <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
            <multiuse-button size="small" type="danger" icon="el-icon-close" :click="deleteIds.bind()">删除</multiuse-button>
           <!-- <multiuse-button size="small" icon="el-icon-upload"  @click="showImportFun()">导入</multiuse-button> -->
          </template>
        </FilterTable>
      </Spin>
      <BaseDialog
        :visible.sync="visibleAdd"
        :title="'图解车型新增'"
        width="850px"
        destroyOnClose
        :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      >
        <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
      </BaseDialog>
      <BaseDialog
        :visible.sync="visibleEdit"
        :title="'图解车型编辑'"
        width="850px"
        destroyOnClose
        :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      >
        <EditForm :rowData="rowData" @close="editclose" @save="editsave"></EditForm>
      </BaseDialog>
       <BaseDialog style="min-height: 80vh;" :visible.sync="showImport" width="80vw" title="图解车型批量导入"
                  destroyOnClose
                  :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }">
        <ExcelImport
          ref="import"
          template-file-name="图解车型导入模板.xlsx"
          :importRules="importRules"
          :onComplete="importComplete"
          @close="showImport = false"
        />
      </BaseDialog>

    </div>
  </Spin>
</template>
<script>
import { getToken, getAppId, getUserId } from '@/assets/js/auth';
import { getModelList,getCarModelArray,piliangshanchu,postImportCarModels } from '@/api/graphic/carModelSettings/index.js';
import ExcelImport from '@/components/ExcelImport';
import { getPart } from '@/api/dictionary/index';
import {dictionary} from'@/utils/dictMixin';
import AddForm from './addForm.vue';
import EditForm from './editForm.vue';
export default {
  props: {

  },
  components: {
    ExcelImport,
    AddForm,
    EditForm
  },
  mixins: [dictionary],
  data() {
    return {
      dataList: [],
      rowData: {},
      params: {},
      visible: false,
      disableds: true,
      showImport: false,
      collapse: false,
      visibleEdit: false,
      fetchapi: getModelList,
      topFilterInit: this.topFilterInitFun(),
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中系统
      visibleAdd: false,
      loading: false,
      loading1: false,
      fileList: [],
      importRules: [
        {prop: 'modelCode', title: '车型代码',rule: {required: true, message: '车型代码不能为空'}},
        {prop: 'modelName', title: '车型名称',rule: {required: true, message: '车型名称不能为空'}},
      ],
    };
  },
  created() {
  },
  methods: {
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      // console.log(this.selectedRows);
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    //导入
    importComplete(datas, callback) {
      const errorData = []
      datas.forEach((item, index1) => {
        const indexarr = []
        datas.forEach((i, index2) => {
          if (
            i.modelCode === item.modelCode &&
            i.modelName === item.modelName &&
            index1 !== index2) {
            indexarr.push(index2 + 1)
          }
        })
        if (indexarr.length) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `与第${indexarr.join(',')}行图解车型信息重复`
          })
        }
      })
      if (errorData.length) {
        callback(errorData)
      }
      else {
        postImportCarModels(datas).then(res => {
          if(res.resultCode == 200) {
            if(res.data.status){
              this.showImport = false
              this.$notify.success({title: '提示信息', message: '批量导入成功'});
              callback()
              this.infoClose({ type:'refresh' });
            }else{
              callback(res.data.errorData)
            }
          } else {
            callback([{errormsg: '服务器运行异常'}])
          }
        })
      }
    },
    infoClose(rData) {
      this.visibleDrawer = false;
      if (rData.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    handleExceed(error) {
      this.loading = false;
    },
    beforeUpload() {
      this.loading = true;
    },
    add() {
      this.visibleAdd = true;
    },
    closeAdd() {
      this.visibleAdd = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    editclose() {
      this.visibleEdit = false;
    },
    emitFun(val) {
      this.rowData = val;
      this.visibleEdit = true;
    },
    editsave() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    saveExcel() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    close() {
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    save(obj) {
      this.topFilterInit.find((x) => x.fieldName == 'model').initialValue = obj[0].address;
      this.visible = false;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
      // console.log(val);
    },
    //批量删除
    async deleteIds() {
      if (this.selectedRows.length > 0) {
        this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let str = '';
          this.selectedRows.map((x) => {
            str += x.modelId + ',';
          });
          const res = await piliangshanchu( str );
          this.fetchParams = { ...this.fetchParams };
          this.loading = false;
          return this.$notify.success({ title: '提示信息', message: '删除成功！' });
        });
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行删除！' });
      }
    },
    //搜索数据
    topFilterInitFun() {
      // 车型代码、车型名称、
      return [
        {
          type: 'INPUT',
          label: '车型代码',
          fieldName: 'modelCode',
          placeholder: '请输入',
          initialValue: '',
          rules: [{ max: 20, message: '长度不能大于20个字符', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '车型名称',
          fieldName: 'modelName',
          placeholder: '请输入.',
          initialValue: '',
          rules: [{ max: 20, message: '长度不能大于20个字符', trigger: 'blur' }]
        }
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        //临时注释 {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 80,
        //   render: (props, h) => {
        //     return (
        //       <div style="text-align:center">
        //         <multiuse-button size="mini" type="text" onClick={() => this.emitFun(props.row)}>
        //           编辑
        //         </multiuse-button>
        //       </div>
        //     );
        //   },
        // },
        // 车型代码、车型名称、创建人、创建时间、修改人、修改时间
        { title: '车型代码', dataIndex: 'modelCode', sorter: true },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: '创建人', dataIndex: 'createdByName', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', dateFormat:'yyyy-MM-dd HH:mm:ss', sorter: true },
        { title: '修改人', dataIndex: 'updatedByName', sorter: true },
        { title: '修改时间', dataIndex: 'updatedAt', dateFormat:'yyyy-MM-dd HH:mm:ss', sorter: true }
      ];
    },
  },
};
</script>

<style lang="less" scoped></style>
